<template>
  <a-button type="outline" @click="handleClick">AI 生成题目</a-button>
  <a-drawer
    :width="340"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="false"
    unmountOnClose
  >
    <template #title>AI 生成题目</template>
    <div>
      <a-form
        :model="form"
        label-align="left"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item label="应用id">
          {{ appId }}
        </a-form-item>
        <a-form-item field="questionCount" label="题目数量">
          <a-input-number
            min="0"
            max="20"
            v-model="form.questionCount"
            placeholder="请输入题目数量"
          />
        </a-form-item>
        <a-form-item field="optionCount" label="选项数量">
          <a-input-number
            min="0"
            max="6"
            v-model="form.optionCount"
            placeholder="请输入选项数量"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              :loading="submitting"
              type="primary"
              html-type="submit"
              style="width: 120px"
            >
              {{ submitting ? "生成中" : "一键生成" }}
            </a-button>
            <a-button
              :loading="submitting"
              style="width: 120px"
              @click="doSSESubmit"
            >
              {{ sseSubmitting ? "生成中" : "实时生成" }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { defineProps, reactive, ref, withDefaults } from "vue";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { aiGenerateQuestionUsingPost } from "@/api/questionController";
import { isDev } from "@/request";

interface Props {
  appId: string;
  onSuccess?: (result: API.QuestionContentDTO[]) => void;
  onSSESuccess?: (result: API.QuestionContentDTO) => void;
  onSSEStart?: (event: any) => void;
  onSSEClose?: (event: any) => void;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});

const form = reactive({
  optionCount: 2,
  questionCount: 10,
} as API.AiGenerateQuestionRequest);

const visible = ref(false);
const submitting = ref(false);
const sseSubmitting = ref(false);

const handleClick = () => {
  visible.value = true;
};
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};

const handleSubmit = async () => {
  if (!props.appId) {
    return;
  }
  submitting.value = true;
  const res = await aiGenerateQuestionUsingPost({
    appId: props.appId as any,
    ...form,
  });
  if (res.data.code === 0 && res.data.data && res.data.data.length > 0) {
    if (props.onSuccess) {
      props.onSuccess(res.data.data);
    } else {
      message.success("生成题目成功");
    }
    // 关闭抽屉
    handleCancel();
  } else {
    message.error("生成题目失败，" + res.data.message);
  }
  submitting.value = false;
};

const doSSESubmit = async () => {
  if (!props.appId) {
    return;
  }
  sseSubmitting.value = true;
  // 创建 SSE 请求
  const eventSource = new EventSource(
    (isDev
      ? "http://localhost:8101/api/question/ai_generate/sse"
      : "https://yudada-backend-115107-5-1315421160.sh.run.tcloudbase.com") +
      `?appId=${props.appId}&questionCount=${form.questionCount}&optionCount=${form.optionCount}`,
    { withCredentials: true }
  );
  // 接收消息
  eventSource.onmessage = function (event) {
    console.log(event.data);
    props.onSSESuccess?.(JSON.parse(event.data));
  };
  // 报错或连接关闭时触发
  eventSource.onerror = function (event) {
    // 如果后端已经关闭连接那么前端也会执行这个onerror，前端也要关不然会一直重连
    if (event.eventPhase == EventSource.CLOSED) {
      console.log("关闭连接");
      eventSource.close();
      props.onSSEClose?.(event);
    }
  };
  eventSource.onopen = function (event) {
    console.log("建立连接");
    props.onSSEStart?.(event);
    handleCancel();
  };
  sseSubmitting.value = false;
};
</script>
